#!/usr/bin/env python
# -*- coding:utf-8 -*-
from rest_framework import serializers
from .models import OAuthQQUser
from django_redis import get_redis_connection
from users.models import User


class QQTokenSerializer(serializers.Serializer):
    # 定义字段，由于models中的模型类字段只有user和openid，它不能满足对数据的校验，所以这里不能用ModelSerializer
    access_token = serializers.CharField(label="操作token")
    mobile = serializers.RegexField(label="手机号", regex=r'^1[345789]\d{9}$')
    password = serializers.CharField(label="密码", min_length=6, max_length=20)
    sms_code = serializers.CharField(label="短信验证码", min_length=6, max_length=6)

    def validate(self, attrs):
        #　验证openid
        access_token = attrs.get("access_token")
        mobile = attrs.get("mobile")
        sms_code = attrs.get("sms_code")
        password = attrs.get("password")
        #　通过access_token换取openid
        openid = OAuthQQUser.get_openid_by_token(access_token)
        if openid is None:

            raise serializers.ValidationError("openid有错误")
        attrs["openid"] = openid
        # 校验短信验证码
        # １.链接数据库
        redis_conn = get_redis_connection('code')
        # ２．获取短信验证码
        redis_text = redis_conn.get("sms_%s"%mobile)
        if redis_text is None:
            raise serializers.ValidationError("短信验证码已过期")

        if redis_text.decode() != sms_code:
            raise serializers.ValidationError("短信验证码输入有误")

        # 校验密码，校验密码首先需要查看用户之前是否有没有注册，如果注册了，则进行密码校验，没有注册，则创建用户
        # １．根据手机号查找用户
        try:
            user = User.objects.get(mobile=mobile)
        except User.DoesNotExist:
            # 如果用户之前没有注册则需要创建，在序列化器中创建用户需要实现create方法，所以需要单独创建，创建后，视图调用序列化器保存时自动调用
            pass
        else:
            # 如果用户注册过，则先验证密码，直接绑定用户
            if not user.check_password(password):
                raise serializers.ValidationError("密码输入有误")

            attrs["user"] = user
            return attrs


    def create(self, validated_data):
        user = validated_data.get("user")
        openid = validated_data.get("openid")
        # 如果用户之前没有注册则进行创建用户
        if user is None:
            user = User.objects.create(
                username = validated_data.get("mobile"),
                password = validated_data.get("password"),
                mobile = validated_data.get('mobile')
            )
            user.set_password(validated_data["password"])
            user.save()
        # 把用户信息和openid进行绑定
        OAuthQQUser.objects.create(
            user = user,
            openid = openid
        )
        return user
